package top.wshape1.shiziapi.uaa.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import top.wshape1.shiziapi.uaa.filter.JwtAuthorizationTokenFilter;
import top.wshape1.shiziapi.uaa.security.MyRedirectStrategy;
import top.wshape1.shiziapi.uaa.security.OAuth2LoginFailureHandler;
import top.wshape1.shiziapi.uaa.security.OAuth2LoginSuccessHandler;
import top.wshape1.shiziapi.uaa.security.RedisOAuth2AuthorizationRequestRepository;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2023-08-22
 */

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private JwtAuthorizationTokenFilter jwtAuthorizationTokenFilter;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private OAuth2LoginSuccessHandler oAuth2LoginSuccessHandler;

    @Bean
    public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        // 记得一定要放行/error
                        // 放行/oauth2/**是因为用户可能绑定gitee或github
                        .requestMatchers("/token/**", "/error", "/oauth2/**", "/user/memberPage", "/user/name").permitAll()
                        .requestMatchers("/login", "/reg/**", "/forget/**").anonymous()
                        .anyRequest().authenticated()
                )
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .formLogin(AbstractHttpConfigurer::disable)
                .logout(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable)
                .oauth2Login(login -> login
                        .authorizationEndpoint(a -> a
                                .baseUri("/oauth2/authorization")
                                .authorizationRedirectStrategy(new MyRedirectStrategy())
                                .authorizationRequestRepository(new RedisOAuth2AuthorizationRequestRepository(redisTemplate))
                        )
                        .redirectionEndpoint(r -> r.baseUri("/oauth2/callback/{registrationId}"))
                        .successHandler(oAuth2LoginSuccessHandler)
                        .failureHandler(new OAuth2LoginFailureHandler())
                )
                .addFilterBefore(jwtAuthorizationTokenFilter, UsernamePasswordAuthenticationFilter.class)
        ;

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


}
